const Service = require('egg').Service

class CourseColumnService extends Service {
  async index() {
    const { ctx, app } = this
    // 获取当前栏目
    const curColumn = await ctx.find('CourseColumn', {}, 'findAll')
    const tmp = []
    if (curColumn.length > 0) {
      curColumn.forEach(item => {
        tmp.push(item.dataValues.channelId)
      })
    }
    const courseColumnUrl = `${app.config.moocDomain}/web/j/indexBeanV3.getCategoryInfo.rpc?csrfKey=${app.config.moocCookie.NTESSTUDYSI}`
    const res = await ctx.helper.curlPost(courseColumnUrl)
    // 从缓存中获取是否有这条记录，有则更新，无则新建
    const { data } = res
    if (+data.code === 0) {
      const postData = []
      data.result.forEach(item => {
        const dict = {}
        const pattern = /\/(\d*)(\.htm)/g
        const channelId = pattern.exec(item.targetUrl)[1]
        if (!tmp.includes(channelId)) {
          dict.channelId = channelId
          dict.channelName = item.channelName
          postData.push(dict)
        }
      })
      const columnRes = await ctx.bulkCreate('CourseColumn', postData)
      return columnRes
    }
  }
}

module.exports = CourseColumnService
